// run the program once all content has been loaded.
document.addEventListener('DOMContentLoaded', function() {
    // define variables.
    var canvas = document.getElementById('canvas'),
        doodler = new window.doodler(canvas),
        x = -1,
        y = -1,
        previousX = -1,
        previousY = -1,
        gridSpacing = 40;

    // define events.
    canvas.addEventListener('mousedown', mousedown);
    canvas.addEventListener('mouseup', mouseup);
    window.addEventListener('load', main);
    window.addEventListener('keydown', panCamera);
    window.addEventListener('resize', fitCanvasToWindow);

    // define properties.
    
    // define functions.
    function drawGrid() {
        for (var x = 0; x < canvas.width; x += gridSpacing) {
            doodler.drawLine(x, 0, x, canvas.height, 1, '#EEE');
        }
        for (var y = 0; y < canvas.height; y += gridSpacing) {
            doodler.drawLine(0, y, canvas.width, y, 1, '#EEE');
        }
    };

    function fitCanvasToWindow() {
        doodler.setCanvasSize(window.innerHeight, window.innerWidth);
    };

    function mousedown(event) {
        mousemove(event);
        canvas.addEventListener('mousemove', mousemove);
    };

    function mouseup(event) {
        canvas.removeEventListener('mousemove', mousemove);
    };

    function mousemove(event) {
        if (x > -1 && y > -1) {
            previousX = x,
            previousY = y;
        }
        x = gridSpacing * Math.floor(event.pageX / gridSpacing),
        y = gridSpacing * Math.floor(event.pageY / gridSpacing);

        if (x != previousX || y != previousY) {
            highlight(x, y);
        }
    };

    function highlight(x, y) {
        canvas.getContext('2d').fillStyle = 'rgba(0, 0, 0, 0.05)';
        canvas.getContext('2d').fillRect(x, y, gridSpacing, gridSpacing);
    };

    function main() {
        fitCanvasToWindow();
        doodler.startDoodling();
    };

    function panCamera() {
        doodler.camera.panLeft(5);
    };
});